package com.szsfm.vehiclemanagement.http.okhttp;

import com.orhanobut.logger.Logger;
import com.szsfm.vehiclemanagement.http.http.HttpManager;
import com.szsfm.vehiclemanagement.http.http.HttpResponse;
import com.szsfm.vehiclemanagement.http.http.HttpResponseCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by zhoubigbo on 2017/11/3.
 */
public class OkhttpManager extends HttpManager {

    private static OkHttpClient mOkhttpClient;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("application/octet-stream");


    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //   builder.cookieJar(new OkhttpCookieJar());
        builder.connectTimeout(OkhttpConfig.CONNECT_TIME_OUT, TimeUnit.SECONDS);
        builder.retryOnConnectionFailure(OkhttpConfig.isRetryOnConnFaily);
        //builder.addInterceptor(new OkhttpLog());
        mOkhttpClient = builder.build();
    }

    @Override
    public void get(String url, final HttpResponseCallback callback) {
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        Call call = mOkhttpClient.newCall(builder.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callback != null) {
                    HttpResponse fail = new HttpResponse();
                    fail.setContent(callback.toString());
                    callback.onCallback(fail);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                String bodyString = body.string();
                if (callback != null) {
                    HttpResponse success = new HttpResponse();
                    success.setContent(bodyString);
                    callback.onCallback(success);
                }
            }
        });
    }

    @Override
    public void uploadImages(String url, List<String> paths, HttpResponseCallback callback) {

    }

    private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("image/jpg");//MediaType.parse("text/x-markdown; charset=utf-8");

    @Override
    public void uploadImages(String url, File file,final String filename, String plate, final HttpResponseCallback callback) {
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_MARKDOWN, file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("", "", fileBody)
                .addFormDataPart("filename",filename)
                .addFormDataPart("plate",plate)
                .build();
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url);
        requestBuilder.post(requestBody);
        Request request = requestBuilder.build();
        mOkhttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.d("onFailure:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Logger.d("onResponse:" + response.body().string());
                if (callback!=null){
                    HttpResponse r = new HttpResponse();
                    r.setContent(filename);
                    callback.onCallback(r);
                }
            }
        });
    }

    public byte[] file2bytes(byte[] buf, String filename, String plate) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            String s1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n" + "  <soap12:Body>\n" + "    <UpdateFile xmlns=\"http://test.noidcxy.cn/API/\">\n" + "      <content>";
            baos.write(s1.getBytes());
            //baos.write(buf);
            baos.write("a".getBytes());
            String s3 = "</content>\n";
            String s4 = "      <filenames>" + filename + "</filenames>\n";
            String s5 = "      <plate>" + plate + "</plate>\n";
            String s6 = "    </UpdateFile>\n" + "  </soap12:Body>\n" + "</soap12:Envelope>";
            baos.write((s3 + s4 + s5 + s6).getBytes());
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** *//**
     * 文件转化为字节数组

     */
    public static byte[] getBytesFromFile(File f){
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (Exception e){
            Logger.d(""+e.getMessage());
        }
        return null;
    }
}
